package com.mllweb.blog.core.regex;

import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则匹配工具
 */
public class RegexUtils {
    /**
     * 匹配邮箱
     *
     * @param email
     * @return
     */
    public static boolean testEmail(String email) {
        Pattern pattern = Pattern.compile(RegexPattern.EMAIL.getValue());
        Matcher matcher = pattern.matcher(email);
        return matcher.find();
    }

    /**
     * 匹配手机
     *
     * @param phone
     * @return
     */
    public static boolean testPhone(String phone) {
        Pattern pattern = Pattern.compile(RegexPattern.PHONE.getValue());
        Matcher matcher = pattern.matcher(phone);
        return matcher.find();
    }

    /**
     * 自定义匹配
     *
     * @param regex 正则
     * @param text
     * @return
     */
    public static boolean testCustom(String regex, String text) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        return matcher.find();
    }

    /**
     * 自定义匹配获取匹配文本
     * @param regex 正则
     * @param text
     * @return
     */
    public static String testCustomText(String regex, String text) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return "";
        }
    }

}
